package com.aiton.bamin.changtukepiao.Zeverything.everything_fragment;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.aiton.administrator.shane_library.shane.upgrade.UpgradeUtils;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.administrator.shane_library.shane.utils.HTTPUtils;
import com.aiton.administrator.shane_library.shane.utils.UILUtils;
import com.aiton.administrator.shane_library.shane.utils.VersionUtils;
import com.aiton.administrator.shane_library.shane.utils.VolleyListener;
import com.aiton.bamin.changtukepiao.Bchangtukepiao.constant.ConstantTicket;
import com.aiton.bamin.changtukepiao.R;
import com.aiton.bamin.changtukepiao.Zeverything.EveryThingSoftInfoActivity;
import com.aiton.bamin.changtukepiao.Zeverything.MineInfoActivity;
import com.aiton.bamin.changtukepiao.Zeverything.SmsLoginActivity;
import com.aiton.bamin.changtukepiao.Zeverything.constant.EverythingConstant;
import com.aiton.bamin.changtukepiao.Zeverything.model.Upgrade;
import com.aiton.bamin.changtukepiao.Zutils.DataCleanManager;
import com.aiton.bamin.changtukepiao.Zutils.IsQQorWeiXinAvilible;
import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.alibaba.sdk.android.feedback.util.IWxCallback;
import com.android.volley.VolleyError;
import com.ecloud.pulltozoomview.PullToZoomScrollViewEx;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class MineEverythingFragment01 extends Fragment implements View.OnClickListener {

    private String mPhoneNum;
    private String mId;
    private boolean isLogined;
    private View mInflate;
    private TextView mTextView_unLogin;
    private RelativeLayout mRela_login;
    private TextView mTextView_login;
    private RelativeLayout mLoginED;
    private TextView mTextView_feedBackCount;
    private boolean isOpenFeedBack = false;
    private boolean isDownIcon = false;
    private PullToZoomScrollViewEx scrollView;
    private ScrollView mPullRootView;
    private IWxCallback callback = new IWxCallback() {
        @Override
        public void onSuccess(final Object... objects) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    int count = (int) objects[0];
                    if (isOpenFeedBack) {
                        count = 0;
                    }
                    if (count == 0) {
                        mTextView_feedBackCount.setText("");
                    } else {
                        mTextView_feedBackCount.setText("+" + count);
                    }
                    isOpenFeedBack = false;
                }
            });
        }

        @Override
        public void onError(int i, String s) {

        }

        @Override
        public void onProgress(int i) {
        }
    };
    private RelativeLayout mRl_mine_evething_clear_diskcache;
    private TextView mTv_diskcache_num;
    private TextView mTv_curr_version;
    private RelativeLayout mRl_check_curr_version;
    private Upgrade mUpgrade;
    private ImageView mImageView_headIcon;
    private String mImage;

    public MineEverythingFragment01() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (mInflate == null) {
            mInflate = inflater.inflate(R.layout.fragment_mine_everything01, null);
            findID();
            initUI();
            setListener();
        }
        return mInflate;
    }

    private void setListener() {
        mLoginED.setOnClickListener(this);
        mPullRootView.findViewById(R.id.rl_mine_evething_soft_info).setOnClickListener(this);
        mPullRootView.findViewById(R.id.rela_feedback).setOnClickListener(this);
        mRl_mine_evething_clear_diskcache.setOnClickListener(this);
        mRl_check_curr_version.setOnClickListener(this);
    }

    private void findID() {
        loadViewForCode();
        mTextView_unLogin = (TextView) mPullRootView.findViewById(R.id.textView_unLogin);
        mRela_login = (RelativeLayout) mPullRootView.findViewById(R.id.rela_login);
        mTextView_login = (TextView) mPullRootView.findViewById(R.id.textView_login);
        mLoginED = (RelativeLayout) mPullRootView.findViewById(R.id.loginED);
        mTextView_feedBackCount = (TextView) mPullRootView.findViewById(R.id.textView_feedBackCount);
        mRl_mine_evething_clear_diskcache = (RelativeLayout) mPullRootView.findViewById(R.id.rl_mine_evething_clear_diskcache);
        mTv_diskcache_num = (TextView) mPullRootView.findViewById(R.id.tv_diskcache_num);
        mTv_curr_version = (TextView) mPullRootView.findViewById(R.id.tv_curr_version);
        mRl_check_curr_version = (RelativeLayout) mPullRootView.findViewById(R.id.rl_check_curr_version);
        mImageView_headIcon = (ImageView) mPullRootView.findViewById(R.id.imageView_headIcon);
    }

    private void initUI() {
        try {
            PackageInfo packageInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0);
            String versionName = packageInfo.versionName;
            mTv_curr_version.setText("检查更新" + "(" + versionName + ")");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void loadViewForCode() {
        scrollView = (PullToZoomScrollViewEx) mInflate.findViewById(R.id.scroll_view);
        View headView = LayoutInflater.from(getActivity()).inflate(R.layout.profile_head_view, null, false);
        View zoomView = LayoutInflater.from(getActivity()).inflate(R.layout.profile_zoom_view, null, false);
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.profile_content_view, null, false);
        scrollView.setHeaderView(headView);
        scrollView.setZoomView(zoomView);
        scrollView.setScrollContentView(contentView);
        mPullRootView = scrollView.getPullRootView();
        DisplayMetrics localDisplayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(localDisplayMetrics);
        int mScreenWidth = localDisplayMetrics.widthPixels;
        LinearLayout.LayoutParams localObject = new LinearLayout.LayoutParams(mScreenWidth, (int) (10.0F * (mScreenWidth / 24.0F)));
        scrollView.setHeaderLayoutParams(localObject);
    }

    /**
     * -------------获取缓存大小-----------------
     */
    private String getSize() {
        String totalCacheSize = null;
        try {
            totalCacheSize = DataCleanManager.getTotalCacheSize(getActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return totalCacheSize;
    }

    @Override
    public void onStart() {
        super.onStart();
        //检查apk缓存
        mTv_diskcache_num.setText(getSize());
        initLogin();
    }

    private void initLogin() {
        SharedPreferences sp = getActivity().getSharedPreferences("isLogin", Context.MODE_PRIVATE);
        mPhoneNum = sp.getString("phoneNum", "");
        mId = sp.getString("id", "");
        mImage = sp.getString("image", "");
        if ("".equals(mPhoneNum)) {
            isLogined = false;
            mTextView_unLogin.setVisibility(View.VISIBLE);
            mRela_login.setVisibility(View.INVISIBLE);
            mTextView_login.setVisibility(View.INVISIBLE);
            mImageView_headIcon.setImageResource(R.mipmap.a02);
        } else {
            isLogined = true;
            mTextView_unLogin.setVisibility(View.INVISIBLE);
            mRela_login.setVisibility(View.VISIBLE);
            mTextView_login.setVisibility(View.VISIBLE);
            mTextView_login.setText(mPhoneNum.substring(0,3)+"****"+mPhoneNum.substring(7,11));
            if ("".equals(mImage)){
                setIcon();
            }else {
                if (!isDownIcon) {
                    UILUtils.displayImageNoAnimNoCache(mImage, mImageView_headIcon, false);
                }else{
                    setIcon();
                }
                isDownIcon=true;
            }
        }
    }

    private void setIcon() {
        String Path = "/upload/" + mPhoneNum + "upload.jpeg";
        File pictureFile = new File(Environment.getExternalStorageDirectory(), Path);
        if (pictureFile.exists()) {
            Uri uri = Uri.fromFile(pictureFile);
            Bitmap bitmap = decodeUriAsBitmap(uri);
            mImageView_headIcon.setImageBitmap(bitmap);
        }else{
            mImageView_headIcon.setImageResource(R.mipmap.a02);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode== EverythingConstant.ISUPDATEICON&&resultCode==EverythingConstant.ISUPDATEICON){
            Log.e("onActivityResult", "顺序");
            isDownIcon=false;
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.loginED:
                if (isLogined) {
                    intent.setClass(getActivity(), MineInfoActivity.class);
                    startActivityForResult(intent, EverythingConstant.ISUPDATEICON);
                    animFromSmallToBigIN();
                } else {
                    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_SMS)
                            != PackageManager.PERMISSION_GRANTED) {
                        //申请WRITE_EXTERNAL_STORAGE权限
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_SMS},
                                EverythingConstant.RequestAndResultCode.PERMISSION_READ_SMS);
                    } else {
                        intent.setClass(getActivity(), SmsLoginActivity.class);
                        startActivity(intent);
                        animFromSmallToBigIN();
                    }
                }
                break;
            case R.id.rl_mine_evething_soft_info:
                intent.setClass(getActivity(), EveryThingSoftInfoActivity.class);
                startActivity(intent);
                animFromSmallToBigIN();
                break;
            case R.id.rela_feedback:
                boolean qqClientAvailable = IsQQorWeiXinAvilible.isQQClientAvailable(getActivity());
                if (qqClientAvailable) {
                    String url = "mqqwpa://im/chat?chat_type=wpa&uin=270942626";
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                } else {
                    //第二个参数是appkey，就是百川应用创建时候的appkey
                    FeedbackAPI.initAnnoy(getActivity().getApplication(), "23334901");
                    Map<String, String> map = new HashMap<>();
                    map.put("bgColor", "#ff7d27");
                    map.put("themeColor", "#ff7d27");
                    map.put("enableAudio", "1");
                    FeedbackAPI.setUICustomInfo(map);
                    //可选功能，第二个参数是当前登录的openim账号，如果是匿名账号方式使用，则可以传空的
                    FeedbackAPI.getFeedbackUnreadCount(getActivity().getApplication(), null, callback);
                    //6.0以上系统需要判断权限
                    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {
                        //申请WRITE_EXTERNAL_STORAGE权限
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA},
                                EverythingConstant.RequestAndResultCode.PERMISSION_CAMERA);
                    }
                    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        //申请WRITE_EXTERNAL_STORAGE权限
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                EverythingConstant.RequestAndResultCode.PERMISSION_READ_EXTERNAL_STORAGE);
                    }
                    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.RECORD_AUDIO)
                            != PackageManager.PERMISSION_GRANTED) {
                        //申请WRITE_EXTERNAL_STORAGE权限
                        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.RECORD_AUDIO},
                                EverythingConstant.RequestAndResultCode.PERMISSION_RECORD_AUDIO);
                    } else {
                        //如果发生错误，请查看logcat日志
                        FeedbackAPI.openFeedbackActivity(getActivity());
                        animFromSmallToBigIN();
                        isOpenFeedBack = true;
                    }
                }
                break;
            case R.id.rl_mine_evething_clear_diskcache:
                DataCleanManager.clearAllCache(getActivity());
                mTv_diskcache_num.setText(getSize());
                Toast.makeText(getActivity(), "缓存清除完毕!", Toast.LENGTH_SHORT).show();
                break;
            case R.id.rl_check_curr_version:

                HTTPUtils.get(getActivity(), ConstantTicket.URL.UP_GRADE, new VolleyListener() {
                    public void onResponse(String json) {
                        mUpgrade = GsonUtils.parseJSON(json, Upgrade.class);
                        int currVersion = VersionUtils.getCurrVersion(getActivity());
                        if (mUpgrade.getVersion() > currVersion) {
                            new AlertDialog.Builder(getActivity())
                                    .setTitle("升级")
                                    .setMessage(mUpgrade.getFeature())
                                    .setPositiveButton("升级",
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                                            != PackageManager.PERMISSION_GRANTED) {
                                                        //申请WRITE_EXTERNAL_STORAGE权限
                                                        ActivityCompat.requestPermissions((Activity) getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EverythingConstant.RequestAndResultCode.PERMISSION_WRITE_EXTERNAL_STORAGE);
                                                    } else {
                                                        UpgradeUtils.checkUpgrade(getActivity(), ConstantTicket.URL.UP_GRADE);
                                                    }
                                                }
                                            }).setNegativeButton("取消", null).show();
                        } else {
                            Toast.makeText(getActivity(), "当前已是最新版本！", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                    }
                });
                break;
        }
    }
    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    /**
     * 从小到大打开动画
     */
    private void animFromSmallToBigIN() {
        getActivity().overridePendingTransition(R.anim.magnify_fade_in, R.anim.fade_out);
    }
}
